package com.qfx.demo.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.qfx.demo.cache.UserCache;
import com.qfx.demo.util.ToolToken;
import com.qfx.demo.vo.SysUser;

import io.jsonwebtoken.Claims;

public class JwtRealm extends AuthorizingRealm {
	
	// 指定凭证匹配器。匹配器工作在认证后，授权前。

	@Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("---------用户权限验证---------");
		// 1.获取用户信息
		// 这里principals.getPrimaryPrincipal()的返回的对象类型与登录验证时
		// new SimpleAuthenticationInfo(user, pwd, this.getName())中的第一个参数的类型需要保持一致
		SysUser user = (SysUser) principals.getPrimaryPrincipal();
		System.out.println("--------2.用户[" + user.getUserName() + "]进行权限验证--------");

		// 2.单独定一个集合对象放置角色信息
		Set<String> roles = new HashSet<String>();
		roles.add(user.getRoleName());

		// 3.查到权限数据，返回授权信息(要包括 上边的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);

		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		System.out.println("---------用户token验证---------");
		String token = (String) authenticationToken.getCredentials();

		// Token解析
		Claims claims = ToolToken.parseJWT(token);
		if (null == claims) {
			throw new AuthenticationException("Token解析失败,可能被修改");
		}

		
		// 获取token所属用户名称
        String userName = claims.getSubject();
        
        // 根据用户名称获取用户信息
        SysUser sysUser = UserCache.getUserCacheMap(userName);;

        if (sysUser == null) {
            throw new AuthenticationException("没有找到当前用户信息");
        }

        SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(sysUser, token, getName());
		
        return authcInfo;
	}
}
